<template>
  <a-spin :spinning="tableLoading">
    <a-card class="app" :hoverable="true">
      <a-row justify="space-between" style="margin-bottom: 20px">
        <a-col :span="12">
          <a-space :size="20">
            <h3 style="display: inline">电键：{{ data.form.docEntry }}</h3>
            <h3 style="display: inline">名称：{{ data.form.objName }}</h3>
            <h3 style="display: inline">
              状态：
              <a-tag color="#87d068">{{ data.form.docStatus }}</a-tag>
            </h3>
            <h3 style="display: inline">
              审核：
              <a-tag color="#87d068">{{ data.form.approved ? '已审核' : '未审核' }}</a-tag>
            </h3>
          </a-space>
        </a-col>
        <a-col :span="12">
          <a-row justify="end">
            <a-button-group>
              <a-button @click="back()">返回</a-button>
              <a-button @click="save()" v-if="!(data.form.docStatus === 'L' || data.form.docStatus === 'C' || data.form.approved || !data.form.edit)"
                >保存
              </a-button>
              <a-button @click="edit()" v-if="!(data.form.docStatus === 'L' || data.form.docStatus === 'C' || data.form.approved || data.form.edit)"
                >编辑
              </a-button>
              <a-button @click="del()" v-if="data.form.docStatus === 'O' && !data.form.approved   && !data.form.edit">删除</a-button>

              <a-button @click="approved()" v-if="!data.form.edit">查看审核</a-button>
              <a-dropdown>
                <a-button v-if="!(data.form.edit || data.form.docStatus === 'L')">更多操作</a-button>
                <template #overlay>
                  <a-menu @click="more">
                    <a-menu-item key="a" v-if="(data.form.docStatus !== 'C')">关闭单据</a-menu-item>
                    <a-menu-item key="b" v-if="(data.form.docStatus === 'C')">打开单据</a-menu-item>
                    <a-menu-item key="c" v-if="!data.form.approved">发起审核</a-menu-item>
                    <a-menu-item key="d" v-if="data.form.approved">取消审核</a-menu-item>
                    <a-menu-item key="e" v-if="(data.form.lista.length === 0)">生成细表</a-menu-item>
                    <a-menu-item key="f" v-if="(data.form.lista.length !== 0)">清空细表</a-menu-item>
                    <a-menu-item key="j" v-if="data.form.approved">分配金额</a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
              <a-button @click="refresh" value="7"> 刷 新</a-button>
            </a-button-group>
          </a-row>
        </a-col>
      </a-row>
      <a-form ref="formRef" :model="data.form" :rules="data.rules" :label-col="{ span: 5 }">
        <a-row class="smart-query-form-row">
          <a-col :span="6">
            <a-form-item label="月期间" name="absId">
              <a-input v-if="data.form.edit" v-model:value="data.form.absId" />
              <span v-else>{{ data.form.absId }}</span>
            </a-form-item>
            <a-form-item label="部门" name="deptId">
              <DepartmentTreeSelect v-if="data.form.edit" :init="false" v-model:value="data.form.deptId" @update:value="change" />
              <span v-else>{{ data.form.deptName }}</span>
            </a-form-item>
            <a-form-item label="制单">
              <span>{{ data.form.createBy + '&nbsp;&nbsp;' + data.form.createTime }}</span>
            </a-form-item>
            <a-form-item label="修改">
              <span>{{ data.form.updateBy + '&nbsp;&nbsp;' + data.form.updateTime }}</span>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="备注">
              <a-textarea v-if="data.form.edit" v-model:value="data.form.remark" :rows="2" />
              <span v-else>{{ data.form.remark }}</span>
            </a-form-item>
          </a-col>
          <a-col :span="8"></a-col>
        </a-row>
        <a-row>
          <a-row class="smart-table-btn-block">
            <div class="smart-table-operate-block">
              <a-button @click="exportaApi()" type="link"> 导出 </a-button>
            </div>
          </a-row>
          <a-row>
            <a-table
              row-key="lineNum"
              :scroll="{ y: 650, x: 3000 }"
              :rowHeight="30"
              :header-height="30"
              :pagination="{
                showSizeChanger: true,
                pageSizeOptions: ['10', '20', '30', '40'],
                defaultPageSize: 20,
                showQuickJumper: true,
              }"
              :columns="columns"
              :data-source="data.form.lista"
              stripe
            >
              <template #bodyCell="{ column, text, record, index }">
                <template v-if="record.edit && column.dataIndex === 'danPostWage'">
                  <a-input-number style="width: 100%" prefix="￥" v-model:value="record.danPostWage" :step="0.01" />
                </template>
                <template v-if="record.edit && column.dataIndex === 'mealWage'">
                  <a-input-number style="width: 100%" prefix="￥" v-model:value="record.mealWage" :step="0.01" />
                </template>
                <template v-if="record.edit && column.dataIndex === 'phoneWage'">
                  <a-input-number style="width: 100%" prefix="￥" v-model:value="record.phoneWage" :step="0.01" />
                </template>
                <template v-if="record.edit && column.dataIndex === 'ageWage'">
                  <a-input-number style="width: 100%" prefix="￥" v-model:value="record.ageWage" :step="0.01" />
                </template>

                <template v-if="record.edit && column.dataIndex === 'reissueWage'">
                  <a-input-number style="width: 100%" prefix="￥" v-model:value="record.reissueWage" :step="0.01" />
                </template>
                <template v-if="record.edit && column.dataIndex === 'otherWage'">
                  <a-input-number style="width: 100%" prefix="￥" v-model:value="record.otherWage" :step="0.01" />
                </template>
                <template v-if="record.edit && column.dataIndex === 'other'">
                  <a-input-number style="width: 100%" prefix="￥" v-model:value="record.other" :step="0.01" />
                </template>
                <template v-if="record.edit && column.dataIndex === 'payableWage'">
                  <span>{{
                    (
                      record.basicWage +
                      record.postWage +
                      record.meritsWage +
                      record.danPostWage +
                      record.mealWage +
                      record.overTimeWage +
                      record.phoneWage +
                      record.ageWage +
                      record.reissueWage +
                      record.otherWage +
                      record.other
                    ).toFixed(2)
                  }}</span>
                </template>
                <template v-if="record.edit && column.dataIndex === 'pensionSafe'">
                  <a-input-number style="width: 100%" prefix="￥" v-model:value="record.pensionSafe" :step="0.01" />
                </template>
                <template v-if="record.edit && column.dataIndex === 'healthSafe'">
                  <a-input-number style="width: 100%" prefix="￥" v-model:value="record.healthSafe" :step="0.01" />
                </template>
                <template v-if="record.edit && column.dataIndex === 'loseSafe'">
                  <a-input-number style="width: 100%" prefix="￥" v-model:value="record.loseSafe" :step="0.01" />
                </template>
                <template v-if="record.edit && column.dataIndex === 'taxableAmount'">
                  <a-input-number style="width: 100%" prefix="￥" v-model:value="record.taxableAmount" :step="0.01" />
                </template>
                <template v-if="record.edit && column.dataIndex === 'persIncoTax'">
                  <a-input-number style="width: 100%" prefix="￥" v-model:value="record.persIncoTax" :step="0.01" />
                </template>
                <template v-if="record.edit && column.dataIndex === 'rebateTax'">
                  <a-input-number style="width: 100%" prefix="￥" v-model:value="record.rebateTax" :step="0.01" />
                </template>
                <template v-if="record.edit && column.dataIndex === 'deduWage'">
                  <a-input-number style="width: 100%" prefix="￥" v-model:value="record.deduWage" :step="0.01" />
                </template>
                <template v-if="record.edit && column.dataIndex === 'payableAmount'">
                  <span>{{
                    (
                      record.basicWage +
                      record.postWage +
                      record.meritsWage +
                      record.danPostWage +
                      record.mealWage +
                      record.overTimeWage +
                      record.phoneWage +
                      record.ageWage +
                      record.reissueWage +
                      record.otherWage +
                      record.other -
                      record.pensionSafe -
                      record.healthSafe -
                      record.loseSafe -
                      record.taxableAmount -
                      record.persIncoTax -
                      record.rebateTax -
                      record.deduWage
                    ).toFixed(2)
                  }}</span>
                </template>
                <template v-if="column.dataIndex === 'type'">
                  {{ record.type === 'A' ? '生产 ' : '办公 ' }}
                </template>

                <template v-if="column.dataIndex === 'action'">
                  <div class="smart-table-operate">
                    <a-button
                      :disabled="data.form.docStatus === 'L' || data.form.docStatus === 'C' || data.form.approved"
                      v-if="!record.edit"
                      @click="lineaEdit(record)"
                      type="link"
                    >
                      <template #icon>
                        <FormOutlined />
                      </template>
                    </a-button>
                    <a-button v-if="record.edit" @click="lineaSave(record)" type="link">
                      <template #icon>
                        <CheckOutlined />
                      </template>
                    </a-button>
                    <a-button
                      :disabled="data.form.docStatus === 'L' || data.form.docStatus === 'C' || data.form.approved"
                      @click="lineaDel(record)"
                      danger
                      type="link"
                    >
                      <template #icon>
                        <DeleteOutlined />
                      </template>
                    </a-button>
                  </div>
                </template>
              </template>
              <template #summary>
                <a-table-summary fixed>
                  <a-table-summary-row>
                    <a-table-summary-cell align="right" v-for="(item, index) in columns" :key="index" :index="1">
                      <template v-if="item.summary">
                        <a-typography-text>
                          {{ combinedNumsc(item.dataIndex).toFixed(2) }}
                        </a-typography-text>
                      </template>
                    </a-table-summary-cell>
                  </a-table-summary-row>
                </a-table-summary>
              </template>
            </a-table>
          </a-row>
        </a-row>
      </a-form>
    </a-card>
  </a-spin>

  <Approvord :approvedData="data.approvedData" :visible="data.visible.approvord" :on-close="onclose"></Approvord>

  <!---------- 查询表单form end ----------->
</template>
<script setup>
  import { computed, onMounted, reactive, ref, watch } from 'vue';
  import { message, Modal } from 'ant-design-vue';
  import { smartSentry } from '/@/lib/smart-sentry';
  import { wageaApi, wageApi } from '/@/api/business/erp/wage-api';
  import { useRouter, useRoute } from 'vue-router';
  import DepartmentTreeSelect from '/@/components/system/department-tree-select/index.vue';
  import { approvordApi } from '/@/api/business/erp/approvord-api';
  import Approvord from '/@/components/business/erp/approved.vue';

  // ---------------------------- 表格列 ----------------------------
  const route = useRoute();
  const router = useRouter();

  const data = reactive({
    form: {
      docEntry: 0,
      objId: '',
      absId: '',
      approved: false,
      docStatus: 'O',
      edit: false,
      lista: [],
    },
    radioGroup: null,
    rules: {
      absId: [{ required: true, message: '请选择月期间' }],
      deptId: [{ required: true, message: '请选择部门' }],
      macName: [{ required: true, message: '请输入设备名称' }],
      macAddress: [{ required: true, message: '请输入设备地址' }],
      basicWage: [{ required: true, message: '' }],
      danPostWage: [{ required: true, message: '' }],
      mealWage: [{ required: true, message: '' }],
      phoneWage: [{ required: true, message: '' }],
      ageWage: [{ required: true, message: '' }],
      reissueWage: [{ required: true, message: '' }],
      otherWage: [{ required: true, message: '' }],
      other: [{ required: true, message: '' }],
      pensionSafe: [{ required: true, message: '' }],
      healthSafe: [{ required: true, message: '' }],
      loseSafe: [{ required: true, message: '' }],
      taxableAmount: [{ required: true, message: '' }],
      persIncoTax: [{ required: true, message: '' }],
      rebateTax: [{ required: true, message: '' }],
      deduWage: [{ required: true, message: '' }],
    },
    model: {
      absId: '',
    },
    editableData: {
      nowDate: null,
    },
    visible: {
      approvord: false,
    },
    approvedData: {
      baseEntry: null,
      tabName: null,
    },
  });
  const columns = ref([
    {
      title: '行号',
      dataIndex: 'lineNum',
      align: 'center',
      width: 100,
    },
    {
      title: '用户编码',
      dataIndex: 'userId',
      align: 'center',
      width: 100,
    },
    {
      title: '用户名称',
      dataIndex: 'userName',
      align: 'right',
      width: 300,
    },
    {
      title: '基本工资',
      dataIndex: 'basicWage',
      align: 'right',
      width: 200,
      summary: true,
    },
    {
      title: '岗位工资',
      dataIndex: 'postWage',
      align: 'right',
      width: 200,
      summary: true,
    },
    {
      title: '绩效工资',
      dataIndex: 'meritsWage',
      align: 'right',
      width: 200,
      summary: true,
    },
    {
      title: '危岗工资',
      dataIndex: 'danPostWage',
      align: 'right',
      width: 200,
      summary: true,
    },
    {
      title: '餐食补贴',
      dataIndex: 'mealWage',
      align: 'right',
      width: 200,
      summary: true,
    },
    {
      title: '加班补贴',
      dataIndex: 'overTimeWage',
      align: 'right',
      width: 200,
      summary: true,
    },
    {
      title: '通讯补贴',
      dataIndex: 'phoneWage',
      align: 'right',
      width: 200,
      summary: true,
    },
    {
      title: '工龄补贴',
      dataIndex: 'ageWage',
      align: 'right',
      width: 200,
      summary: true,
    },
    {
      title: '补发',
      dataIndex: 'reissueWage',
      align: 'right',
      width: 200,
      summary: true,
    },
    {
      title: '其它补贴',
      dataIndex: 'otherWage',
      align: 'right',
      width: 200,
      summary: true,
    },
    {
      title: '其它',
      dataIndex: 'other',
      align: 'right',
      width: 200,
      summary: true,
    },
    {
      title: '应发工资',
      dataIndex: 'payableWage',
      align: 'right',
      width: 200,
      summary: true,
    },
    {
      title: '养老保险',
      dataIndex: 'pensionSafe',
      align: 'right',
      width: 200,
      summary: true,
    },
    {
      title: '医疗保险',
      dataIndex: 'healthSafe',
      align: 'right',
      width: 200,
      summary: true,
    },
    {
      title: '失业保险',
      dataIndex: 'loseSafe',
      align: 'right',
      width: 200,
      summary: true,
    },
    {
      title: '住房公积金',
      dataIndex: 'taxableAmount',
      align: 'right',
      width: 200,
      summary: true,
    },
    {
      title: '个人所得税',
      dataIndex: 'persIncoTax',
      align: 'right',
      width: 200,
      summary: true,
    },
    {
      title: '退税',
      dataIndex: 'rebateTax',
      align: 'right',
      width: 200,
      summary: true,
    },

    {
      title: '工资扣款',
      dataIndex: 'deduWage',
      align: 'right',
      width: 200,
      summary: true,
    },
    {
      title: '应发金额',
      dataIndex: 'payableAmount',
      align: 'right',
      width: 200,
      summary: true,
    },
    {
      title: '对账单电键',
      dataIndex: 'baseEntry',
      align: 'right',
      width: 200,
    },
    {
      title: '来源类型',
      dataIndex: 'type',
      align: 'center',
      width: 100,
    },
    {
      title: '操作',
      dataIndex: 'action',
      width: 100,
      align: 'center',
      fixed: 'right',
    },
  ]);
  const tableLoading = ref(false);
  const formRef = ref();

  function init() {
    if (route.query.type === 'info') {
      data.form.docEntry = route.query.docEntry;
      queryData();
    } else {
      data.form.edit = true;
    }
  }

  onMounted(init);

  function back() {
    router.push({ path: '/erp/wage' });
  }

  function add() {
    data.form.objId = 78;
    data.form.objName = '日历';
    data.form.docStatus = 'O';
    data.form.approved = false;
    data.form.absId = null;
    data.form.deptId = null;
    data.form.deptName = null;
    data.form.remark = null;
    data.form.edit = true;
    data.form.lista = [];
    router.push({ path: '/erp/wagea', query: { type: 'new', docEntry: null } });
  }

  function save() {
    formRef.value
      .validate()
      .then(() => {
        tableLoading.value = true;
        if (data.form.docEntry) {
          wageApi.update(data.form).then((res) => {
            queryData(data.form.docEntry);
            message.success('保存成功！');
          });
        } else {
          wageApi.add(data.form).then((res) => {
            data.form.docEntry = res.data;
            message.success('保存成功！');
            router.push({ path: '/erp/wagea', query: { type: 'info', docEntry: res.data } });
            queryData(res.data);
          });
        }
      })
      .catch((err) => {
        message.error('页面校验失败！');
      });
  }

  function edit() {
    data.form.edit = true;
  }

  // 查询数据
   function queryData() {
    tableLoading.value = true;
    wageApi
      .info(data.form.docEntry)
      .then((res) => {
        data.form = res.data;
      })
      .finally(() => {
        tableLoading.value = false;
      });
  }

  function del() {
    Modal.confirm({
      content: `确认删除（${data.form.docEntry}）`,
      onOk() {
        wageApi.delete(data.form.docEntry).then((res) => {
          message.success('删除成功！');
          router.push({ path: '/erp/wage' });
        });
      },
      cancelText: '取消',
      onCancel() {
        Modal.destroyAll();
      },
    });
  }

  function more({ key }) {
    // 审核处理函数
    if (key === 'a') {
      data.form.docStatus = 'C';
      tableLoading.value = true;
      wageApi.update(data.form).then((res) => {
        tableLoading.value = false;
        queryData();
      });
    } else if (key === 'b') {
      data.form.docStatus = 'O';
      tableLoading.value = true;
      wageApi.update(data.form).then((res) => {
        tableLoading.value = false;
        queryData();
      });
    } else if (key === 'c') {
      approvordApi
        .add({
          docEntry: 0,
          approvLineNum: 2,
          approvType: 'A',
          baseEntry: data.form.docEntry,
          tabName: data.form.objName,
          docStatus: 'O',
          tabId: data.form.objId,
          baseVersion: data.form.version,
        })
        .then((res) => {
          queryData();
        });
    } else if (key === 'd') {
      approvordApi
        .add({
          docEntry: 0,
          approvLineNum: 2,
          approvType: 'B',
          baseEntry: data.form.docEntry,
          tabName: data.form.objName,
          docStatus: 'O',
          tabId: data.form.objId,
          baseVersion: data.form.version,
        })
        .then((res) => {
          queryData();
        });
    } else if (key === 'e') {
      tableLoading.value = true;
      wageApi.excute(data.form).then((res) => {
        tableLoading.value = false;
        queryData();
        message.success('执行成功！');
      });
    } else if (key === 'f') {
      tableLoading.value = true;
      wageaApi.delete(data.form.docEntry).then((res) => {
        tableLoading.value = false;
        queryData();
      });
    } else if (key === 'j') {
      tableLoading.value = true;
      wageApi.shareApi(data.form.docEntry).then((res) => {
        tableLoading.value = false;
        queryData();
      });
    }
  }

  function refresh() {
    queryData();
  }

  function change(item, key) {
    data.form.deptName = key;
  }

  // 审核------------------------------------------------------------------------------------------------
  function approved() {
    data.approvedData.baseEntry = data.form.docEntry;
    data.approvedData.tabName = data.form.objName;
    data.visible.approvord = true;
  }

  function onclose() {
    data.visible.approvord = false;
    queryData();
  }

  //----------------------------a----------------------------------

  function onChange(pagination, filters, sorter, { action }) {
    if (action === 'sort') {
      const { order, field } = sorter;
      data.form.lista.sort((a, b) => {
        if (order === 'ascend') {
          return a[field] - b[field];
        } else {
          return b[field] - a[field];
        }
      });
    }
  }

  function exportaApi() {
    wageaApi.export(data.form.docEntry);
  }

  function lineaEdit(key) {
    key.edit = true;
  }

  function lineaDel(item) {
    tableLoading.value = true;
    wageaApi.deleteLine(item).then((res) => {
      tableLoading.value = false;
      queryData();
    });
  }

  function lineaSave(item) {
    formRef.value
      .validate()
      .then((res) => {
        if (res) {
          tableLoading.value = true;
          if (item.lineNum) {
            wageaApi
              .update(item)
              .then((res) => {
                item.edit = false;
                tableLoading.value = false;
                queryData();
              })
              .catch((err) => {
                tableLoading.value = false;
              });
          } else {
            wageaApi
              .add(item)
              .then((res) => {
                item.edit = false;
                tableLoading.value = false;
                queryData();
              })
              .catch((err) => {
                tableLoading.value = false;
              });
          }
        }
      })
      .catch((err) => {
        message.error('页面校验失败！');
      });
  }

  const combinedNumsc = computed(() => (field) => {
    return data.form.lista.reduce((prev, next) => {
      return prev + next[field];
    }, 0);
  });
</script>
